#pragma once

#include <iostream>
#include <string>
#include <poll.h>
#include <memory>
#include "Log.hpp"
#include "Socket.hpp"

using namespace LogModule;
using namespace SocketModule;

const static int gdefaultport = 8888;
const static int gbacklog = 8;
const int gnum = 1024;

class pollServer {

private:
    void accepter() {
        InetAddr client;
        int sockfd = _listenSockFd->Accept(&client);
        if(sockfd >= 0)
        {
            int pos = 0;
            while(pos < _num)
            {
                if(_rfds[pos].fd == defaultfd)
                    break;
                pos++;
            }

            if(pos == _num)
            {
                LOG(LogLevel::WARNING) << "select server full";
                close(sockfd);
            }
            else
            {
                _rfds[pos].fd = sockfd;
                _rfds[pos].events |= POLLIN;
            }
        }
    }

    void recver(int fd, int pos) {
        char buffer[1024];
        ssize_t n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        if(n > 0) {
            buffer[n] = 0;
            std::cout << "client say@ "<< buffer << std::endl;
        }
        else if(n == 0) {
            LOG(LogLevel::INFO) << "clien quit...";
            close(fd);
            _rfds[pos].fd = defaultfd;
            _rfds[pos].events = 0;
            _rfds[pos].revents = 0;
        }
    }

    void handlerEvent() {
        for(int i = 0; i < _num; i++) {
            if(_rfds[i].fd == -1) continue;;
            // 合法sockfd，分类讨论
            // 监听套接字新连接到来或者普通sockfd新数据到来
            int fd = _rfds[i].fd;
            short revents = _rfds[i].revents;
            // 新连接到来
            if(fd == _listenSockFd->Fd()) {
                accepter();
            }
            // 普通数据到来
            else {
                recver(fd, i);
            }
        }
    }

public:
    pollServer(int port = gdefaultport)
        :_port(port)
        ,_listenSockFd(std::make_unique<Socket>())
        ,_isrunning(false)
        ,_num(gnum)
        ,_rfds(new struct pollfd[_num])
    {
        _listenSockFd->BuildTcpSocketMethod(port);
        for(int i = 0; i <_num; i++) {
            _rfds[i].fd = -1;
            _rfds[i].events = 0;
            _rfds[i].revents = 0;
        }

        // 将监听套接字设置到_rfds
        _rfds[0].fd = _listenSockFd->Fd();
        _rfds[0].events |= POLLIN;
    }

    ~pollServer() {
        delete[] _rfds;
    }
    

    void loop() {
        _isrunning = true;
        while(_isrunning) {
            int timeout = -1;
            // rfds也是输出型参数，服务器运行过程中，rfds不断被修改，每次都需要重置
            int res = poll(_rfds, _num, timeout);
            switch(res) {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::INFO) << "time out...";
                break;
            default:
                LOG(LogLevel::DEBUG) << "Event ready..." << res;
                handlerEvent();
                break;
            }
        }
        _isrunning = false;
    }

    void stop() {
        _isrunning = false;
    }
    
private:
    std::unique_ptr<Socket> _listenSockFd;
    int _port;
    bool _isrunning;
    struct pollfd* _rfds;
    int _num;
};